﻿using System;
using System.IO;
using System.Xml.Serialization;
using log4net;

namespace Pixster.Controllers.Helpers
{
    public static class FileHelper<T>
    {
        private static readonly ILog LOG = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static void SaveToDisk(T directoryInfo, string filePath)
        {
            try
            {
                LOG.InfoFormat("Saving file '{0}' to disk.", filePath);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    var serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(stream, directoryInfo);
                }
            }
            catch (Exception ex)
            {
                LOG.ErrorFormat("Error attempting to save file to disk '{0}' - {1}", filePath, ex);
            }
        }

        public static T LoadFromDisk(string filePath)
        {
            if (File.Exists(filePath))
            {
                try
                {
                    LOG.InfoFormat("Loading file '{0}' from disk.", filePath);

                    using (Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        var serializer = new XmlSerializer(typeof(T));
                        return (T)serializer.Deserialize(stream);
                    }
                }
                catch (Exception ex)
                {
                    LOG.ErrorFormat("Error attempting to read file from disk '{0}' - {1}", filePath, ex);
                }
            }

            LOG.WarnFormat("File '{0}' does not exist.", filePath);

            return default(T);
        }
    }
}